package com.example.observertest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Observable<String> observable = getObservable();

                Observer<String> observer = getObserver();

                observable.subscribe(observer);
            }
        });
    }

    private Observable<String> getObservable(){
        //写法2
        Observable<String> observable = Observable.just("大保健", "泡吧");
        return  observable;

        //写法1
//        return Observable.create(new ObservableOnSubscribe<String>() {
//            @Override
//            public void subscribe(ObservableEmitter<String> e) throws Exception {
//                e.onNext("大保健");
//                e.onNext("泡吧");
//
//                e.onComplete();
//            }
//        });
    }

    private  Observer<String> getObserver(){
        return new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe","onSubscribe");
            }

            @Override
            public void onNext(String value) {
                tv.append(value);
                Log.e("onNext","onNext..."+value);
            }

            @Override
            public void onError(Throwable e) {
                Log.e("onError","onError");
            }

            @Override
            public void onComplete() {
                Log.e("onComplete","onComplete");
            }
        };
    }

}
